package ch15;

import ch14.EmptyCollectionException;
import ch14.LinearNode;

/**
 * Created by 春旺 on 2017/10/13.
 */
public class LinkedQueue<T> implements Queue<T> {

        private int count;
        private LinearNode<T> front, rear;
        //-----------------------------------------------------------------
// Creates an empty queue.
//-----------------------------------------------------------------
        public LinkedQueue()
        {
            count = 0;
            front = rear = null;
        }
        //-----------------------------------------------------------------
// Adds the specified element to the rear of this queue.
//-----------------------------------------------------------------
        public void enqueue (T element)
        {
            LinearNode<T> node = new LinearNode<T>(element);
            if (count == 0)
                front = node;
            else
                rear.setNext(node);
            rear = node;
            count++;
        }

    @Override
    public T dequeue() throws EmptyCollectionException{
        LinearNode<T> node = new LinearNode<>();
            T re = front.getElement();
            if(count == 1){
                front =null;
                rear = null;
            }
            else {
               front = front.getNext();
            }
            count --;
        return re;
    }

    @Override
    public T first() {
        T re = front.getElement();
        return re;
    }

    @Override
    public boolean isEmpty() {
            boolean b = true;
            if (count != 0){
                b = false;}
        return b;
    }

    @Override
    public int size() {

        return count;
    }
  @Override
    public String toString(){
            String result = "";
            LinearNode node = new LinearNode();
            node = front;
                while (node != null){
                    result +=node.getElement();
                    node = node.getNext();
                }
            return result;
   }

}
